/*
 * @Author: hongbin
 * @Date: 2022-12-23 20:57:23
 * @LastEditors: hongbin
 * @LastEditTime: 2022-12-24 18:02:44
 * @Description: 添加好友组件
 */
import { FC, memo, NamedExoticComponent, useCallback, useMemo, useState } from "react";
import styled from "styled-components";
import { post } from "../../api";
import { useAuth } from "../../context/AuthProvide";
import { showMessage } from "../../HUI/MessageBar";

interface IProps {
    /**
     * 对方_id
     */
    targetId: string;
    /**
     * 显示文字 默认加好友
     */
    text?: string;
    /**
     * 如果已经是好友了显示的JSX组件
     */
    already?: JSX.Element;
}

const AddFriend: NamedExoticComponent<IProps> = memo(({ targetId, text = "加好友", already }) => {
    const { user } = useAuth();
    const isFriend = useMemo(() => user.friendsList?.map((f) => f.friendId).includes(targetId), []);
    const [loading, setLoading] = useState(false);
    const [sended, setSended] = useState(false);

    const request = useCallback(async () => {
        setLoading(true);
        //TODO 发送好友申请列表
        post("/RequestList/send", {
            targetId,
            senderId: user._id,
            senderName: user.name,
        }).then((d) => {
            showMessage("已发送好友申请", 600);
            setSended(true);
            setLoading(false);
        });
    }, [targetId, user._id, user.name]);

    if (isFriend) return already || null;

    return <Button onClick={sended ? undefined : request}>{sended ? "已发送" : loading ? "加载中..." : text}</Button>;
});

AddFriend.displayName = "AddFriend";

export default AddFriend;

const Button = styled.button`
    min-width: 5vw;
    border-radius: 0.3vw;
    background: #116702;
    border: 3px solid #178d02;
    color: #eee;
    cursor: pointer;
    padding: 0.4vh;
`;
